<?php
/**
 * Description: 评论接口
 *
 * @author      Eden
 * @datetime    2016/12/25 16:31
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Comment_Model extends API_Model
{
    private $counter = 0;
    private $comments = null;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param $params
     */
    public function run($params)
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            // 整理参数
            if (!$this->settleParams($params['comments'])) {
                $error = $this->getError();
                $send['error'] = !empty($error) ? $error : '参数错误';
                break;
            }

            if (!$this->doComments($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $send['state'] = true;
            $send['data'] = [
                'msg' => '评论成功'
            ];

        } while(false);
        $this->output->send($send);
    }

    /**
     * 评论
     * @param array $params
     * @return bool
     */
    private function doComments(Array $params)
    {
        $anonymous = $params['isAnonymous'] == 'yes' ? 1 : 0;
        try {
            $db = clone($this->db);
            $db->trans_start();
            $this->load->helper('security');
            foreach ($this->comments as $com) {
                $goodsId = value($com, 'goodsId', 0);
                $content = value($com, 'content', '');
                $stars = value($com, 'stars', 5);
                $stars = $stars > 5 || $stars < 0 ? 5 : intval($stars);

                if (empty($goodsId) || empty($content)) {
                    $this->setError('参数错误');
                    continue;
                }

                $content = xss_clean($content);
                $content = strip_image_tags($content);
                $content = encode_php_tags($content);

                // base_goods_comment
                $baseGoodsCommentDb = clone($this->db);
                $baseGoodsCommentDb->insert('base_goods_comments', [
                    'goodsId' => $goodsId,
                    'userId' => $params['userId'],
                    'content' => $content,
                    'created' => dateTime(),
                    'goodsStars' => $stars,
                    'anonymous' => $anonymous,
                    'status' => 1
                ]);

                // base_goods
                $baseGoodsDb = clone($this->db);
                $baseGoodsDb->where('id', $goodsId);
                $baseGoodsDb->set('comments', 'comments+1', FALSE);
                $baseGoodsDb->update('base_goods');
            }

            $expressStars = value($params, 'expressStars', 5);
            $expressStars = $expressStars > 5 || $expressStars < 0 ? 5 : $expressStars;
            $expressDb = clone($this->db);
            $expressDb->insert('user_order_express_stars', [
                'orderId' => $params['orderId'],
                'stars' => $expressStars
            ]);

            $orderDb = clone($this->db);
            $orderDb->where('id', $params['orderId']);
            $orderDb->update('user_order', ['commented' => 1]);

            $db->trans_complete();

            if ($db->trans_status()) {
                return true;
            }

            $this->setError('评论失败');
            return false;
        } catch(PDOException $e) {
            $this->setError('评论失败');
        }

        return false;
    }

    /**
     * 整理内容
     * @param $comments
     * @return bool
     */
    private function settleParams($comments)
    {
        if (is_string($comments)) {
            try {
                $com = json_decode($comments, true);
            } catch(Exception $e) {
                $this->setError('评论格式错误');
                return false;
            }

            if (empty($com)) {
                $this->setError('评论格式错误');
                return false;
            }

            $this->comments = $com;
            return true;
        }

        if (is_array($comments)) {
            $this->comments = $comments;
            return true;
        }

        return false;
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams(Array $params)
    {

        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['userId']) || empty($params['orderId'])
            || empty($params['comments']) || empty($params['isAnonymous'])) {
            $this->setError('参数错误');
            return false;
        }

        if (!in_array($params['isAnonymous'], array('yes', 'no'))) {
            $this->setError('参数错误');
            return false;
        }

        return true;
    }
}
